package com.qqq.adminservice.user.service.impl;

import com.qqq.adminapi.appuser.domain.dto.AppUserDTO;
import com.qqq.adminapi.appuser.domain.dto.AppUserListReqDTO;
import com.qqq.adminapi.appuser.domain.dto.UserEditReqDTO;
import com.qqq.adminservice.user.config.RabbitConfig;
import com.qqq.adminservice.user.domain.entity.AppUser;
import com.qqq.adminservice.user.mapper.AppUserMapper;
import com.qqq.adminservice.user.service.IAppUserService;
import com.qqq.commoncore.domain.dto.BasePageDTO;
import com.qqq.commoncore.utils.AESUtil;
import com.qqq.commoncore.utils.BeanCopyUtil;
import com.qqq.commondomain.domain.ResultCode;
import com.qqq.commondomain.exception.ServiceException;
import com.qqq.commonrabbitmq.config.RabbitMqCommonConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * C端用户服务层实现类
 */
@Component
@Slf4j
@RefreshScope
public class AppUserServiceImpl implements IAppUserService {

    @Autowired
    private AppUserMapper appUserMapper;

    @Value("${appuser.info.defaultAvatar}")
    private String defaultAvatar;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 微信注册
     *
     * @param openId 用户微信ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO registerByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            throw new ServiceException("要注册的openId为空！");
        }
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);

        // ⽣成1000到9999之间的随机数
        appUser.setNickName("租房用户" + (int) ((Math.random() * 9000) + 1000));
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setNickName(appUser.getNickName());
        appUserDTO.setOpenId(openId);
        appUserDTO.setAvatar(appUser.getAvatar());
        return appUserDTO;
    }


    /**
     * 根据opneId查询
     *
     * @param openId 用户微信ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            return null;
        }
        AppUser appUser = appUserMapper.selectByOpenId(openId);
        if (null == appUser) {
            log.error("查询⼈员信息失败！openId:{}", openId);
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanCopyUtil.copyProperties(appUser, appUserDTO);
        // 处理手机号
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        return appUserDTO;
    }

    /**
     * 根据phone查询用户信息
     *
     * @param phoneNumber 用户手机号
     * @return C端用户VO
     */
    @Override
    public AppUserDTO findByPhone(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            return null;
        }
        AppUser appUser = appUserMapper.selectByPhoneNumber(
                AESUtil.encryptHex(phoneNumber));
        if (null == appUser) {
            log.error("查询⼈员信息失败！phoneNumber:{}", phoneNumber);
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setNickName(appUser.getNickName());
        appUserDTO.setPhoneNumber(
                AESUtil.decryptHex(appUser.getPhoneNumber()));
        appUserDTO.setAvatar(appUser.getAvatar());
        appUserDTO.setOpenId(appUser.getOpenId());
        return appUserDTO;
    }

    /**
     * 手机号注册
     *
     * @param phoneNumber 用户手机号
     * @return C端用户VO
     */
    @Override
    public AppUserDTO registerByPhone(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException("要注册的手机号为空！");
        }
        AppUser appUser = new AppUser();
        appUser.setPhoneNumber(
                AESUtil.encryptHex(phoneNumber));
        // ⽣成1000到9999之间的随机数
        appUser.setNickName("⽐特租房用户" + (int) ((Math.random() * 9000) + 1000));
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setNickName(appUser.getNickName());
        appUserDTO.setPhoneNumber(phoneNumber);
        appUserDTO.setAvatar(appUser.getAvatar());
        return appUserDTO;
    }

    /**
     * 编辑用户
     *
     * @param userEditReqDTO 用户编辑DTO
     * @return void类型
     */
    /**
     * 编辑用户
     *
     * @param userEditReqDTO 用户编辑DTO
     */
    @Override
    public void edit(UserEditReqDTO userEditReqDTO) {
        // 根据ID查询要编辑的用户
        AppUser appUser = appUserMapper.selectById(userEditReqDTO.getUserId());
        if (appUser == null) {
            throw new ServiceException("用户不存在", ResultCode.INVALID_PARA.getCode());
        }
        // 查到用户，进行编辑操作
        appUser.setNickName(userEditReqDTO.getNickName());
        appUser.setAvatar(userEditReqDTO.getAvatar());
        appUserMapper.updateById(appUser);
        // 发消息通知消费方
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        try {
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, "",
                    appUserDTO);
        } catch (Exception e) {
            log.error("编辑用户发送消息失败", e);
        }
    }

    /**
     * 查询C端用户
     *
     * @param appUserListReqDTO 查询C端用户DTO
     * @return C端用户分页结果
     */
    @Override
    public BasePageDTO<AppUserDTO> getUserList(AppUserListReqDTO appUserListReqDTO) {
        // 先把手机号转变过来
        appUserListReqDTO.setPhoneNumber(AESUtil.encryptHex(appUserListReqDTO.getPhoneNumber()));
        BasePageDTO<AppUserDTO> result = new BasePageDTO<>();
        // 查询总数
        Long totals = appUserMapper.selectCount(appUserListReqDTO);
        if (0 == totals) {
            // 无数据
            result.setTotals(0);
            result.setTotalPages(0);
            result.setList(new ArrayList<>());
            return result;
        }
        // 分页查询
        List<AppUser> appUserList = appUserMapper.selectPage(appUserListReqDTO);
        result.setTotals(Integer.parseInt(String.valueOf(totals)));
        result.setTotalPages(
                BasePageDTO.calculateTotalPages(totals,
                        appUserListReqDTO.getPageSize())
        );
        if (CollectionUtils.isEmpty(appUserList)) {
            // 超过翻⻚
            result.setList(new ArrayList<>());
            return result;
        }
        // 对象列表结果转换
        result.setList(
                appUserList.stream()
                        .map(appUser -> {
                            AppUserDTO appUserDTO = new AppUserDTO();
                            appUserDTO.setUserId(appUser.getId());
                            appUserDTO.setNickName(appUser.getNickName());
                            appUserDTO.setPhoneNumber(
                                    AESUtil.decryptHex(appUser.getPhoneNumber()));
                            appUserDTO.setAvatar(appUser.getAvatar());
                            appUserDTO.setOpenId(appUser.getOpenId());
                            return appUserDTO;
                        }).collect(Collectors.toList())
        );
        return result;
    }

    /**
     * 根据用户id查询
     *
     * @param userId 用户ID
     * @return C端用户DTO
     */
    @Override
    public AppUserDTO findById(Long userId) {
        if (null == userId) {
            return null;
        }
        AppUser appUser = appUserMapper.selectById(userId);
        if (null == appUser) {
            log.error("查询⼈员信息失败！userId:{}", userId);
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setNickName(appUser.getNickName());
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        appUserDTO.setAvatar(appUser.getAvatar());
        appUserDTO.setOpenId(appUser.getOpenId());
        return appUserDTO;
    }


    /**
     * 根据ids获取⼈员列表
     *
     * @param userIds 用户ID列表
     * @return C端用户DTO列表
     */
    @Override
    public List<AppUserDTO> getUserList(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Arrays.asList();
        }
        List<AppUser> appUserList = appUserMapper.selectBatchIds(userIds);
        return appUserList.stream()
                .map(appUser -> {
                    AppUserDTO appUserDTO = new AppUserDTO();
                    BeanCopyUtil.copyProperties(appUser, appUserDTO);
                    appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
                    appUserDTO.setUserId(appUser.getId());
                    return appUserDTO;
                }).collect(Collectors.toList());
    }
}

